package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"srv/models/mysql"
	"srv/pkg"

	"srv/internal/svc"
	"srv/sesame"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *sesame.OrderAddRequest) (*sesame.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.GetGoods(in.GoodsId)
	if err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	orderSn := uuid.NewString()
	amount := g.GoodsPrice * float64(in.Num)

	o := mysql.Order{
		Model:       gorm.Model{},
		UserId:      int(in.UserId),
		OrderSn:     orderSn,
		Num:         int(in.Num),
		Amount:      amount,
		OrderType:   1,
		OrderStatus: 0,
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, err
	}
	totalAmount := fmt.Sprintf("%.2f", amount)
	pay := pkg.AliPay{
		Subject:     "订单标题",
		OutTradeNo:  orderSn,
		TotalAmount: totalAmount,
	}
	url := pay.Pay()
	return &sesame.OrderAddResponse{
		Url:     url,
		OrderId: int64(o.ID),
	}, nil
}
